<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElEmpty } from 'element-plus'
import { ShoppingCart, Picture } from '@element-plus/icons-vue'

// 定义商品接口
interface Product {
  id: number
  name: string
  price: number
  stock: number
  img_url: string
  description: string
  create_date: string
}

const route = useRoute()
const searchResults = ref<Product[]>([])
const searchTerm = ref('')
const isLoading = ref(false)

// 所有产品数据
const allProducts: Product[] = [
  {
    "id": 1,
    "name": "土豆丝",
    "price": 12,
    "stock": 50,
    "img_url": "土豆丝.jpg",
    "description": "经典家常菜，酸辣可口",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 2,
    "name": "开水白菜",
    "price": 10,
    "stock": 45,
    "img_url": "开水白菜.jpg",
    "description": "川菜名品，清淡鲜美",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 3,
    "name": "糖醋排骨",
    "price": 32,
    "stock": 60,
    "img_url": "糖醋排骨.jpg",
    "description": "酸甜可口，肉质鲜嫩",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 4,
    "name": "红烧肉",
    "price": 50,
    "stock": 30,
    "img_url": "红烧肉.jpg",
    "description": "色泽红亮，肥而不腻",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 5,
    "name": "西湖醋鱼",
    "price": 88,
    "stock": 55,
    "img_url": "西湖醋鱼.jpg",
    "description": "杭州名菜，酸甜鲜美",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 6,
    "name": "西红柿炒鸡蛋",
    "price": 15,
    "stock": 40,
    "img_url": "西红柿炒鸡蛋.jpg",
    "description": "家常美味，营养丰富",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 7,
    "name": "锅包肉",
    "price": 36,
    "stock": 35,
    "img_url": "锅包肉.jpg",
    "description": "东北名菜，外酥里嫩",
    "create_date": "2025-09-03 10:46:58"
  },
  {
    "id": 8,
    "name": "麻婆豆腐",
    "price": 11,
    "stock": 65,
    "img_url": "麻婆豆腐.jpg",
    "description": "麻辣鲜香，下饭神器",
    "create_date": "2025-09-03 10:46:58"
  },
]

// 执行搜索
const performSearch = (query: string) => {
  isLoading.value = true
  searchTerm.value = query
  
  setTimeout(() => {
    if (!query.trim()) {
      searchResults.value = []
    } else {
      searchResults.value = allProducts.filter(product => 
        product.name.toLowerCase().includes(query.toLowerCase()) ||
        product.description.toLowerCase().includes(query.toLowerCase())
      )
    }
    
    isLoading.value = false
    if (searchResults.value.length > 0) {
      ElMessage.success(`找到 ${searchResults.value.length} 个相关结果`)
    } else if (query.trim()) {
      ElMessage.info('没有找到相关商品')
    }
  }, 300)
}

// 添加到购物车功能
const addToCart = (product: Product) => {
  console.log('添加商品到购物车:', product.name)
  
  try {
    const existingCart = localStorage.getItem('cart')
    let cartItems = existingCart ? JSON.parse(existingCart) : []
    
    const existingItemIndex = cartItems.findIndex((item: any) => item.id === product.id)
    
    if (existingItemIndex !== -1) {
      cartItems[existingItemIndex].quantity++
      ElMessage.success(`已增加 ${product.name} 的数量`)
    } else {
      const newCartItem = {
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: 1,
        image: `/src/assets/images/${product.img_url}`,
        description: product.description
      }
      cartItems.push(newCartItem)
      ElMessage.success(`已添加 ${product.name} 到购物车`)
    }

    localStorage.setItem('cart', JSON.stringify(cartItems))
    window.dispatchEvent(new Event('cartUpdated'))
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败，请重试')
  }
}

// 监听路由变化
onMounted(() => {
  if (route.query.q) {
    performSearch(route.query.q as string)
  }
})
</script>

<template>
  <div class="search-view">
    <div class="search-header">
      <h2 v-if="searchTerm">搜索结果: "{{ searchTerm }}"</h2>
      <h2 v-else>搜索美食</h2>
      <p v-if="searchResults.length > 0">找到 {{ searchResults.length }} 个相关商品</p>
    </div>
    
    <div v-loading="isLoading" class="results-container">
      <el-empty v-if="searchResults.length === 0 && !isLoading && searchTerm" description="没有找到相关商品，请尝试其他关键词" />
      
      <el-row v-else :gutter="20" justify="center" style="margin: 20px auto; max-width: 1200px;">
        <el-col 
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="6"
          v-for="product in searchResults" 
          :key="product.id"
          style="margin-bottom: 20px;"
        >
          <el-card class="product-card" shadow="hover">
            <el-image 
              :src="`/src/assets/images/${product.img_url}`" 
              :alt="product.name"
              style="height: 200px; width: 100%;"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>

            <div style="padding: 15px;">
              <h3 style="margin: 0 0 10px 0; color: #333; text-align: center;">
                {{ product.name }}
              </h3>
              
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <el-text type="danger" size="large" style="font-weight: bold;">
                  ¥{{ product.price }}
                </el-text>
                <el-text type="info" size="small">
                  库存: {{ product.stock }}
                </el-text>
              </div>

              <el-text 
                type="info" 
                size="small" 
                style="display: block; margin-bottom: 15px; line-height: 1.4; text-align: center;"
              >
                {{ product.description }}
              </el-text>

              <el-button 
                type="primary" 
                size="small" 
                @click="addToCart(product)"
                style="width: 100%;"
                :disabled="product.stock <= 0"
              >
                <template #icon>
                  <el-icon><ShoppingCart /></el-icon>
                </template>
                {{ product.stock <= 0 ? '已售罄' : '加入购物车' }}
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.search-view {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
}

.product-card {
  border-radius: 12px;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  border-color: #409EFF;
  transform: translateY(-2px);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  background: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .search-view {
    padding: 10px;
  }
  
  .el-col {
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .product-card {
    margin: 0 5px;
  }
}
</style>